(function() {

	var skill = {
		save: function() {
			db.update(config.dbname.bina, this._id, this);
		},
		destroy: function() {
			db.remove(config.dbname.bina, this._id);
		},
		_getUserMap: function() {
			var user_map = this.user_map;
			if (!user_map) {
				user_map = this.user_map = {}
				this.save();
			}
			return user_map;
		},
		_getUserInfoListByRecommender: function(recommender_id) {
			var user_map = this._getUserMap();
			var user_info_list = [];
			Object.keys(user_map).forEach(function(user_id) {
				var buyer_info = user_map[user_id];
				if (buyer_info.recommender_id == recommender_id) {
					user_info_list.push(buyer_info);
				}
			});
			return user_info_list;
		},
		getUser: function(user_id) {
			var user_map = this._getUserMap();
			return user_map[user_id];
		},
		getUserIdList: function() {
			var user_map = this._getUserMap();
			return Object.keys(user_map);
		},
		hasBuyed: function(user_id) {
			var user_map = this._getUserMap();
			return user_map.hasOwnProperty(user_id);
		},
		//非安全，添加用户到分销列表中，从而获取分销权限
		_addUser: function(user_id, recommender_id, is_silence) {
			var user_map = this._getUserMap();
			if (user_map[user_id]) {
				is_silence || throwCusError("指定用户已经拥有此商品的分销权限");
				return;
			};
			user_map[user_id] = {
				user_id: user_id,
				recommender_id: recommender_id,
				achs: [],
				first_acc: 0,
				//动态生成，节省内存
				// first_bina_ach_list: [],
				second_acc: 0,
				//动态生成，节省内存
				// second_bina_ach_list: [],
				third_acc: 0,
				// third_bina_ach_list: []
			};
			var user = UserCon.get(user_id);
			user._addBinaAch(this._id);
			this.save();
		},
		//非安全，冻结用户的分销权限
		_lockUser: function(user_id) {
			var user_map = this._getUserMap();
			if (user_map[user_id]) {
				user_map[user_id].is_lock = true;
				this.save();
			}
		},
		_unlockUser: function(user_id) {
			var user_map = this._getUserMap();
			if (user_map[user_id]) {
				user_map[user_id].is_lock = false;
				this.save();
			}
		},
		//判断用户可否再将订单记录加入bina对象中
		canAddAchAble: function(user_id) {
			var user_map = this._getUserMap();
			var bus = BusCon.get(this.bus_id);
			return this._canAddAchAble(user_id, user_map, bus);
		},
		//代码片段
		_canAddAchAble: function(user_id, user_map, bus) {
			if (user_map[user_id] && user_map[user_id].achs && user_map[user_id].achs.length > 0 && !bus.getPerm().can_multi_bina) {
				return false
			}
			return true;
		},
		addAch: function(ach_id, bina_buff_config) {
			var self = this;
			var user_map = this._getUserMap();
			var ach = AchCon.get(ach_id);
			var bus = BusCon.get(ach.info.bus_id);
			if (!bus.getPerm().can_goods_be_bina) {
				return;
			}
			var user_id = ach.info.user_id;
			var _can_multi_bina = !!bus.getPerm().can_multi_bina;
			console.log("bus.getPerm().can_multi_bina:", _can_multi_bina);
			if (!this._canAddAchAble(user_id, user_map, bus)) {
				//如果已经有购买记录了，就不进行记录，
				console.log("bina已经有购买记录：", this.goods_id, user_id);
				return
			}
			//返利配置
			var _is_senior_user = bus._getSeniorBinaUserList().indexOf(user_id) !== -1;
			var _to_senior_bina_cash = bina_buff_config.to_senior_bina_cash
			var _can_senior = _to_senior_bina_cash && typeof bina_buff_config.senior === "object"
				//如果商品高级分销规则所需累积消费金额设为0的话，高级分销权限就全部取消，无法享有
			if (_is_senior_user && _can_senior) {
				bina_buff_config = bina_buff_config.senior;
			}
			var config_first = bina_buff_config.first || 0;
			var config_second = bina_buff_config.second || 0;
			var config_third = bina_buff_config.third || 0;
			var guide_bina_buff = bus.getGuideBinaBuff();
			var guide_bina_buff_config = guide_bina_buff ? guide_bina_buff.config : bina_buff_config;
			var guide_config_first = guide_bina_buff_config.first || 0;
			var guide_config_second = guide_bina_buff_config.second || 0;
			var guide_config_third = guide_bina_buff_config.third || 0;
			//返利的商品
			var bina_goods_list = [];
			var bina_cash = 0;
			var bina_first_acc = 0;
			var bina_second_acc = 0;
			var bina_third_acc = 0;
			var guide_bina_first_acc = 0;
			var guide_bina_second_acc = 0;
			var guide_bina_third_acc = 0;
			var goods_info;
			//计算返利值
			ach.info.goods_info.some(function(goods_and_num) {
				var goods_id = goods_and_num.goods._id;
				if (self.goods_id === goods_id) { //只管自己这个商品，BUFF是按照商品来触发的，不用管其它商品
					if (bus.isBinaGoods(goods_id)) {
						var bina = BinaCon.build(goods_id);
						//购买者是否还未购买过此商品
						if (!bina.hasBuyed(user_id) || _can_multi_bina) {
							//如果是第一次购买，无法使用推荐返利，而是使用商品分销
							//如果禁止重复购买分销，只能算一个商品
							var _current_bina_cash = goods_and_num.goods.cash * (_can_multi_bina ? goods_and_num.num : 1);
							bina_cash += _current_bina_cash;
							var goods_custom_bina_buff = bus.getGoodsBinaBuff(goods_id);
							var _config_first = config_first;
							var _config_second = config_second;
							var _config_third = config_third;

							var _guide_config_first = guide_config_first;
							var _guide_config_second = guide_config_second;
							var _guide_config_third = guide_config_third;

							if (goods_custom_bina_buff) {
								_config_first = goods_custom_bina_buff.config.first;
								_config_second = goods_custom_bina_buff.config.second;
								_config_third = goods_custom_bina_buff.config.third;

								_guide_config_first = goods_custom_bina_buff.config.first;
								_guide_config_second = goods_custom_bina_buff.config.second;
								_guide_config_third = goods_custom_bina_buff.config.third;
							}
							console.log("_config_first, _config_second, _config_third:", _config_first, _config_second, _config_third);
							bina_first_acc += _current_bina_cash * _config_first;
							bina_second_acc += _current_bina_cash * _config_second;
							bina_third_acc += _current_bina_cash * _config_third;

							guide_bina_first_acc += _current_bina_cash * _guide_config_first;
							guide_bina_second_acc += _current_bina_cash * _guide_config_second;
							guide_bina_third_acc += _current_bina_cash * _guide_config_third;

							bina_goods_list.push(goods_id);
						}
					}
					goods_info = goods_and_num.goods;
					return true;
				}
			});
			//A一定要买，所以B尽管比A先买，A后面又付款，也无法让这单子生效
			var buyer_info = user_map[user_id] || (user_map[user_id] = {
				user_id: user_id,
				recommender_id: ach.info.guide_id || ach.info.recommender_id,
				achs: [],
				first_acc: 0,
				//动态生成，节省内存
				// first_bina_ach_list: [],
				second_acc: 0,
				//动态生成，节省内存
				// second_bina_ach_list: [],
				third_acc: 0,
				// third_bina_ach_list: []
				//冻结，不可参与分销
				//is_lock: false=true;
			});
			if (!buyer_info.achs) {
				buyer_info.achs = [];
			}
			//兼容以前的版本
			if (buyer_info.ach_id) {
				buyer_info.achs.push({
					ach_id: buyer_info.ach_id,
					goods_list: buyer_info.bina_goods_list,
					bina_cash: buyer_info.bina_cash
				});
				delete buyer_info.ach_id;
				delete buyer_info.bina_goods_list;
				delete buyer_info.bina_cash;
			}
			buyer_info.achs.push({
				ach_id: ach_id,
				goods_list: bina_goods_list,
				bina_cash: bina_cash
			});
			console.log("BINA:", [
				bina_first_acc,
				bina_second_acc,
				bina_third_acc,
				guide_bina_first_acc,
				guide_bina_second_acc,
				guide_bina_third_acc,
			]);
			//永久分销的开通，尝试性的
			bus.tryAddUserToForeverBinaUserListByCumulativeCash(user_id);

			//分销
			//没买过就没法返利，尽管后面这个人买了，除非设置了“分享分销”的特权
			var _bina_no_need_buy = bus.getPerm().bina_no_need_buy;
			(function() {
				console.log("BINA:buyer_info:", buyer_info);

				//一级关系
				var first_info = user_map[buyer_info.recommender_id];
				if (!first_info) {
					console.log("bus.getPerm().bina_no_need_buy:", bus.getPerm().bina_no_need_buy);
					if (_bina_no_need_buy && buyer_info.recommender_id) {
						var first_user = UserCon.get(buyer_info.recommender_id);
						first_info = user_map[first_user._id] = {
							user_id: first_user._id,
							recommender_id: first_user.getBusRecommender(ach.info.bus_id),
							achs: [],
							first_acc: 0,
							//动态生成，节省内存
							// first_bina_ach_list: [],
							second_acc: 0,
							//动态生成，节省内存
							// second_bina_ach_list: [],
							third_acc: 0,
							// third_bina_ach_list: []
						};
						first_user._addBinaAch(self._id);
					} else {
						return
					}
				}
				if (!first_info.is_lock) {
					first_info.first_acc += bus.isGuideUser(first_info.user_id) ? guide_bina_first_acc : bina_first_acc;
					var first_bina_ach_list = first_info.first_bina_ach_list || (first_info.first_bina_ach_list = []);
					first_bina_ach_list.push(ach_id); //TODO:这边应该把bina_first_acc也记录下来
					midEvent.emit("bina.first_recommender.get_acc", bus._id, user_id, first_info.user_id, bina_first_acc.toFixed(2), goods_info)
					console.log("BINA:first_info:", first_info);
				}

				//二级关系
				var second_info = user_map[first_info.recommender_id];
				if (!second_info) {
					if (_bina_no_need_buy && first_info.recommender_id) {
						var second_user = UserCon.get(first_info.recommender_id);
						second_info = user_map[second_user._id] = {
							user_id: second_user._id,
							recommender_id: second_user.getBusRecommender(ach.info.bus_id),
							achs: [],
							first_acc: 0,
							//动态生成，节省内存
							// first_bina_ach_list: [],
							second_acc: 0,
							//动态生成，节省内存
							// second_bina_ach_list: [],
							third_acc: 0,
							// third_bina_ach_list: []
						};
						second_info._addBinaAch(self._id);
					} else {
						return
					}
				}
				if (!second_info.is_lock) {
					second_info.second_acc += bus.isGuideUser(second_info.user_id) ? guide_bina_second_acc : bina_second_acc;
					var second_bina_ach_list = first_info.second_bina_ach_list || (first_info.second_bina_ach_list = []);
					second_bina_ach_list.push(ach_id);
					console.log("BINA:second_info:", second_info);
				}

				//三级关系
				if (!bus.getPerm().can_bina_to_third) {
					return
				}
				var third_info = user_map[second_info.recommender_id];
				if (!third_info) {
					if (_bina_no_need_buy && second_info.recommender_id) {
						var third_user = UserCon.get(second_info.recommender_id);
						third_info = user_map[third_user._id] = {
							user_id: third_user._id,
							recommender_id: third_user.getBusRecommender(ach.info.bus_id),
							achs: [],
							first_acc: 0,
							//动态生成，节省内存
							// first_bina_ach_list: [],
							second_acc: 0,
							//动态生成，节省内存
							// second_bina_ach_list: [],
							third_acc: 0,
							// third_bina_ach_list: []
						};
						third_info._addBinaAch(self._id);
					} else {
						return
					}
				}
				if (!third_info.is_lock) {
					third_info.third_acc = (parseFloat(third_info.third_acc) || 0) + (bus.isGuideUser(third_info.user_id) ? guide_bina_third_acc : bina_third_acc);
					var third_bina_ach_list = second_info.third_bina_ach_list || (second_info.third_bina_ach_list = []);
					third_bina_ach_list.push(ach_id);
					console.log("BINA:third_info:", third_info);
				}

				// console.log("商品分销信息：", buyer_info, first_info, second_info, third_info);
			}());

			//购买者记录这个分销订单
			var user = UserCon.get(user_id);
			user._addBinaAch(this._id);

			if (!_is_senior_user && _can_senior) { //如果不是高级分销人员。而且有设定高级分销规则
				if (user._getBinaBus(bus._id)[0].total_bina_cash >= _to_senior_bina_cash) {//累积消费金额达到对应额度
					bus.addUserToSeniorBinaUserList(user_id);
				}
			}

			console.log(user_id, user._getBinaAchList());

			this.save();
		},
		//非安全，将积分额度转成到用户账户上的可用金额
		_to_BusUser_money: function(money_num) {
			//格式化
			money_num = parseFloat(money_num) || 0;
			if (money_num <= 0) {
				throwCusError("输入金额有误")
			}
			var bus = BusCon.get(this.bus_id);
			//计算抵消金额所需的积分
			var _acc = bus.recommendMoneyToAcc(money_num);
			//上限校验
			console.log(_acc, this.acc)
			if (_acc > this.acc) {
				throwCusError("可用金额不足")
			}
			console.log(this.acc, this.total_acc);
			this.acc -= _acc;
			this.total_acc += _acc;
			console.log(this.acc, this.total_acc);

			var bus_user = BusUserCon.get(BusUserCon.build(this));
			bus_user._addMoney(money_num);

			this.save();
		}
	}
	module.exports = skill;
	var db = require("../db/index");
	var BinaCon = require("../bina/_con");
	var UserCon = require("../user/_con");
	var BusCon = require("../bus/_con");
	var GoodsCon = require("../goods/_con");
	var AchCon = require("../ach/_con");
	var PayAchCon = require("../pay_ach/_con");
	var CommentCon = require("../comment/_con");
	var EvaluationCon = require("../eval/_con");
	var ClassifyCon = require("./_con");
	var config = require("../_include/config");
	var data_cut = require("../_include/data_cut");
	var $Array = require("../_include/$.Array");
	var $Object = require("../_include/$.Object");
	var helper = require("../_include/helper");
	var midEvent = require("../../middleware/index");

}());